
package system.base;

import java.sql.ResultSet;

import javax.servlet.ServletOutputStream;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import system.LoginContext;
import system.data.InHeadPageData;

import com.hitrust.gs.lib.GSBaseConstants;

import framework.core.ConstDefine;
import framework.core.DBConnection;
import framework.core.DBEngine;
import framework.core.DBResult;
import framework.core.DateUtil;
import framework.core.IHandler;
import framework.core.ILoginContext;
import framework.core.Logger;
import framework.core.ObjectList;
import framework.core.PageData;
import framework.core.SearchEvent;
import framework.core.SrvContext;
import framework.core.StringUtil;
/*
	Author    :Wing
	CreateTime:2008-02-20 17:30:49
*/
public class InHeadSrv extends IHandler
{
	private boolean isTel=false;
	public InHeadSrv() 
	{
		super();
	}
	private void deleteInHead(DBConnection con,SrvContext context) throws Exception
	{
		String[] ids = context.getParameterValues("ids");
		InHead obj = null;
		for(int i=0;i<ids.length;i++)
		{
			obj = InHead.fetch(con,ids[i]);
			if(obj!=null) obj.delete(con);
		}
	}
	private void saveInHead(DBConnection con,SrvContext context,ILoginContext loginContext) throws Exception
	{
		String id = context.getString("Id",null);
		InHead obj;
		if((id==null)||(id.equals("")))   //add
		{
			obj = InHead.fetch();
    	}
    	else                     //update
    	{
    		obj = InHead.fetch(con,id);
    	}
		InHeadPageData data = (InHeadPageData)PageData.fromForm(context,InHeadPageData.class);
		context.setValue("InHeadPageData",data);
		obj.fill(data);
		obj.save(con);
	}
	private void listInHead(DBConnection con,SrvContext context,ILoginContext loginContext,String path) throws Exception
	{
	    boolean isFirst = context.getBoolean("isFirst");
	    String isFirstVisit = "false";
		InSubSearchEvent event = (InSubSearchEvent)SearchEvent.fromForm(context,InSubSearchEvent.class);
		String []warehouseCodes = null;
		String[] warehouseCodesSplit;
        String warehouseCodesService ="";
        String[] warehouseTreeCodes ;
        String[] inBillBalanceMode;
		if (isFirst)
		{
        	warehouseTreeCodes = new String[]{loginContext.getLoginWarehouseCode()}; 
		    warehouseCodes = new String[]{loginContext.getLoginWarehouseCode()}; 
            isFirstVisit = "true";
		}
		else
		{
			inBillBalanceMode = context.getParameterValues("inBillBalanceMode");
        	if (inBillBalanceMode == null||inBillBalanceMode.length==0||inBillBalanceMode[0].equals(""))
            {
            
            }else{

                String tCurDT= com.hitrust.gs.util.date.DateUtil.getCurrentDate("yyyy-MM-dd");
             	event.setEndInTime(tCurDT+" 23:59:59");
             	tCurDT=tCurDT.substring(0, tCurDT.length()-2);
            	event.setStartInTime(tCurDT+"01 00:00:00");
            	event.setBalanceMode(inBillBalanceMode[0]);
            	event.setStatus("1");
            }
    		warehouseCodes = context.getParameterValues("WarehouseCodes");
    		if (warehouseCodes == null||warehouseCodes.length==0||warehouseCodes[0].equals(""))
            {
                warehouseCodes = new String[]{"--1"};
                warehouseTreeCodes = new String[]{"--1"};
            }else{
            	warehouseCodesSplit = warehouseCodes[0].split(",");
            	for (int j = 0; j < warehouseCodesSplit.length; j++) {
	        		String warehouseObjectListService = Warehouse.fetchWarehousesForString(con, warehouseCodesSplit[j]);
    				String[] service = warehouseObjectListService.split(",");
    				for (int i = 0; i < service.length; i++) {
    					warehouseCodesService += service[i]+",";
    				}
				}
            	warehouseCodes = warehouseCodesService.split(",");
            	warehouseTreeCodes =  context.getParameterValues("WarehouseCodes");
            }
            isFirstVisit = "false";
		}
        event.setWarehouseTreeCodes(warehouseTreeCodes);
        event.setWarehouseCodes(warehouseCodes);
        event.setWarehouseCodeUser(ConstDefine.getWildCard(loginContext.getLoginWarehouseCode()));
        //event.setStatus(InSub.STATUS_AVALIBLE);
		context.setSessionValue("InSubSearchEvent",event);
		//增加配置文件 判断湖南巴士计划价 2009-06-04
		if(GSBaseConstants.PLANPRICE.equals("true")){
            context.setValue("isPlanprice", "1");
        }else{
            context.setValue("isPlanprice", "0");
        }
	       ProductSearchEvent pevent = (ProductSearchEvent) SearchEvent.fromForm(context, ProductSearchEvent.class);
           context.setSessionValue("ProductSearchEvent", pevent);
		context.setNextUrl(path+"InHeadList.jsp"+"?isFirstVisit="+isFirstVisit);
	}
	private void backInHead(DBConnection con,SrvContext context,String path) throws Exception
	{
		context.setNextUrl(path+"InHeadList.jsp");
	}
	
	//add by Wing start
    private HSSFCell createCell(HSSFWorkbook aWb, HSSFRow aRow, short column,String aValue){
        HSSFCell tCell = aRow.createCell(column);
        tCell.setEncoding(HSSFCell.ENCODING_UTF_16);
        tCell.setCellValue(aValue);
        return tCell;
    }
    
    private void exportInHead(DBConnection con,SrvContext context,String path) throws Exception
    {
        HSSFWorkbook tWb = new HSSFWorkbook();
        HSSFSheet tSheet = tWb.createSheet();
        tWb.setSheetName(0,"入库统计",HSSFCell.ENCODING_UTF_16);
        HSSFRow tRow = tSheet.createRow((short)0);
        HSSFCell tCell0  = createCell(tWb,tRow,(short)0, "仓库");
        HSSFCell tCell1  = createCell(tWb,tRow,(short)1, "货位");
        HSSFCell tCell2  = createCell(tWb,tRow,(short)2, "入库单编码");
        HSSFCell tCell3  = createCell(tWb,tRow,(short)3, "入库日期");
        HSSFCell tCell4  = createCell(tWb,tRow,(short)4, "入库类型");
        HSSFCell tCell5  = createCell(tWb,tRow,(short)5, "供应商");
        HSSFCell tCell6  = createCell(tWb,tRow,(short)6, "收料单号");
        HSSFCell tCell7  = createCell(tWb,tRow,(short)7, "网上订单号");
        HSSFCell tCell8  = createCell(tWb,tRow,(short)8, "产品编码");
        HSSFCell tCell9  = createCell(tWb,tRow,(short)9, "产品名称");
        HSSFCell tCell10 = createCell(tWb,tRow,(short)10,"单位");
        HSSFCell tCell11 = createCell(tWb,tRow,(short)11,"规格");
        HSSFCell tCell12 = createCell(tWb,tRow,(short)12,"型号");
        HSSFCell tCell13 = createCell(tWb,tRow,(short)13,"品牌");
        HSSFCell tCell14 = createCell(tWb,tRow,(short)14,"数量");
        HSSFCell tCell15 = createCell(tWb,tRow,(short)15,"单价");
        HSSFCell tCell16 = createCell(tWb,tRow,(short)16,"金额");
        HSSFCell tCell17 = createCell(tWb,tRow,(short)17,"结算模式");
        HSSFCell tCell18 = createCell(tWb,tRow,(short)18,"管理员");
        HSSFCell tCell19 = createCell(tWb,tRow,(short)19,"创建人");
        HSSFCell tCell20 = createCell(tWb,tRow,(short)20,"创建时间");
        HSSFCell tCell21 = createCell(tWb,tRow,(short)21,"备注");
        if(isTel){
        	 HSSFCell tCell22 = createCell(tWb,tRow,(short)22,"进价");
        }
        InSubSearchEvent event = (InSubSearchEvent)context.getSessionValue("InSubSearchEvent");
        event.setPageNum(1);
        event.setPageSize(ConstDefine.INT_MAX);
        
        String status = event.getStatus();
        String statustp = event.getStatus();
        if(statustp == null){
            statustp = InSub.STATUS_AVALIBLE;
        }
        else if("".equals(statustp)){
            statustp = InSub.STATUS_AVALIBLE;
        }
        event.setStatus(statustp);
        
        ObjectList list = InSub.fetch().search(con,event);
      //-----------------------
        String sql = "select sum(Product_Money) from T_IN_SUB ";
        DBResult dbrs = DBEngine.doSelect(con, sql, event.toConditions());
        ResultSet rs = dbrs.getRs();
        String allMoney = "0";
        if(rs.next()){
            allMoney = dbrs.getRs().getString(1) == null ? "0" : dbrs.getRs().getString(1);    
        }
        dbrs.clear();
        allMoney = StringUtil.showPrice(allMoney);
        
        event.setStatus(status);
        //------------------------
        int j = 0;
        for(int i=0;i<list.size();i++)
        {
            InSub obj = (InSub)list.get(i);
            InHead head = null;
            head = InHead.fetchByInBillId(con,obj.getInBillId());
            if (head != null) {
                Product pro = Product.fetchByConcentricityCode(con,obj.getProductCode());
                if (pro == null) pro = new Product();
                HSSFRow row = tSheet.createRow((short)++j);
                HSSFCell cell0  = createCell(tWb,row,(short)0, head.viewWarehouseName(con));
                HSSFCell cell1  = createCell(tWb,row,(short)1, obj.viewPositionName(con));
                HSSFCell cell2  = createCell(tWb,row,(short)2, obj.viewInBillCode(con));
                HSSFCell cell3  = createCell(tWb,row,(short)3, head.viewInTime(con));
                HSSFCell cell4  = createCell(tWb,row,(short)4, head.viewInType(con));
                HSSFCell cell5  = createCell(tWb,row,(short)5, head.viewProviderName(con));
                HSSFCell cell6  = createCell(tWb,row,(short)6, head.viewRemark(con));
                HSSFCell cell7  = createCell(tWb,row,(short)7, head.viewSendBillCode(con));
                HSSFCell cell8  = createCell(tWb,row,(short)8, obj.viewProductCode(con));
                HSSFCell cell9  = createCell(tWb,row,(short)9, pro.viewName(con));
                HSSFCell cell10 = createCell(tWb,row,(short)10,pro.viewProductUnit(con));
                HSSFCell cell11 = createCell(tWb,row,(short)11,pro.viewSpec(con));
                HSSFCell cell12 = createCell(tWb,row,(short)12,pro.viewModel(con));
                HSSFCell cell13 = createCell(tWb,row,(short)13,pro.viewProductBrand(con));
                HSSFCell cell14 = createCell(tWb,row,(short)14,StringUtil.showCount(obj.viewProductCount(con)));
                HSSFCell cell15 = createCell(tWb,row,(short)15,StringUtil.showPrice(obj.viewProductPrice(con)));
                HSSFCell cell16 = createCell(tWb,row,(short)16,StringUtil.showPrice(obj.viewProductMoney(con)));
                HSSFCell cell17 = createCell(tWb,row,(short)17,obj.viewBalanceMode(con));obj.getSubRemark();
                WarehouseStaff staff = WarehouseStaff.fetch(con,obj.getKeeperStaffId());
                if(staff==null){
                    HSSFCell cell18 = createCell(tWb,row,(short)18,"");
                }else{
                    HSSFCell cell18 = createCell(tWb,row,(short)18,staff.getName());
                }
                HSSFCell cell19 = createCell(tWb,row,(short)19,obj.getCreateUser());
                HSSFCell cell20 = createCell(tWb,row,(short)20,obj.getCreateTime());
                HSSFCell cell21 = createCell(tWb,row,(short)21,obj.getSubRemark());
                if(isTel){
                	 HSSFCell cell22 = createCell(tWb,row,(short)22,""+obj.getActualPrice());
                }
            }
        }
        

        HSSFRow row = tSheet.createRow((short)list.size()+1);
        HSSFCell cell0  = createCell(tWb,row,(short)0, "");
        HSSFCell cell1  = createCell(tWb,row,(short)1, "");
        HSSFCell cell2  = createCell(tWb,row,(short)2, "");
        HSSFCell cell3  = createCell(tWb,row,(short)3, "");
        HSSFCell cell4  = createCell(tWb,row,(short)4, "");
        HSSFCell cell5  = createCell(tWb,row,(short)5, "");
        HSSFCell cell6  = createCell(tWb,row,(short)6, "");
        HSSFCell cell7  = createCell(tWb,row,(short)7, "");
        HSSFCell cell8  = createCell(tWb,row,(short)8, "");
        HSSFCell cell9  = createCell(tWb,row,(short)9, "");
        HSSFCell cell10 = createCell(tWb,row,(short)10, "");
        HSSFCell cell11 = createCell(tWb,row,(short)11, "");
        HSSFCell cell12 = createCell(tWb,row,(short)12, "");
        HSSFCell cell13 = createCell(tWb,row,(short)13, "");
        HSSFCell cell14 = createCell(tWb,row,(short)14, "");
        HSSFCell cell15 = createCell(tWb,row,(short)15, "");
        HSSFCell cell16 = createCell(tWb,row,(short)16, "");
        HSSFCell cell17 = createCell(tWb,row,(short)17, "");
        HSSFCell cell18 = createCell(tWb,row,(short)18, "");
        HSSFCell cell19 = createCell(tWb,row,(short)19, "");
        HSSFCell cell20 = createCell(tWb,row,(short)20, "当前查询入库货物金额合计:");
        HSSFCell cell21 = createCell(tWb,row,(short)21, allMoney);
        DateUtil date = new DateUtil();
        String year = date.getYear() + "";
        String month = date.getMonth() + "";
        if (date.getMonth() < 10) month = "0" + date.getMonth();
        String day = date.getDay() + "";
        if (date.getDay() < 10) day = "0" + date.getDay();
        String hour = date.getHour() + "";
        if (date.getHour() < 10) hour = "0" + date.getHour();
        String minute = date.getMinute() + "";
        if (date.getMinute() < 10) minute = "0" + date.getMinute();
        String second = date.getSecond() + "";
        if (date.getSecond() < 10) second = "0" + date.getSecond();
        
        String fileName = "IN_BILL_" + year + "_" + month + "_" + day + "_" + hour + "_" + minute + "_" + second + ".xls";
        context.m_res.setContentType("application/ms-excel");
        context.m_res.addHeader("Content-disposition", "filename="+fileName);
        ServletOutputStream out = context.getServletOutputStream();
        tWb.write(out);
        out.flush();
        out.close();
    }

    //add by Wing end
	
	public void doAction(DBConnection con,SrvContext context,ILoginContext loginContext) throws Exception
	{

		String action_code = context.getActionCode();
		String path = "/system/base/";
		
		if(action_code.equalsIgnoreCase("listInHead"))
		{
            ObjectList warehouseList = Warehouse.fetchAllOrgs(con, loginContext.getLoginWarehouseCode());
            context.setSessionValue("WarehouseListDetail", warehouseList);
			listInHead(con,context,loginContext,path);
			return;
		}
		if(action_code.equalsIgnoreCase("viewInHead"))
		{
			String id = context.getString("Id",null);
			InHead obj = InHead.fetch(con,id);
			context.setValue("InHead",obj);
			context.setNextUrl(path+"InHeadView.jsp");
			return;
		}
		if(action_code.equalsIgnoreCase("deleteInHead"))
		{
			context.setErrorUrl(path+"InHeadList.jsp");
			deleteInHead(con,context);
			backInHead(con,context,path);
			return;
		}
			
		if(action_code.equalsIgnoreCase("toAddInHead"))
		{
			InHead obj = InHead.fetch();
			InHeadPageData data = (InHeadPageData)PageData.fromTable(obj,InHeadPageData.class);
			context.setValue("InHeadPageData",data);
			context.setNextUrl(path+"InHeadEdit.jsp");
			return;
		}
		if(action_code.equalsIgnoreCase("toUpdateInHead"))
		{
			String id = context.getString("Id",null);
			InHead obj = InHead.fetch(con,id);
			InHeadPageData data = (InHeadPageData)PageData.fromTable(obj,InHeadPageData.class);
			context.setValue("InHeadPageData",data);
			context.setNextUrl(path+"InHeadEdit.jsp");
			return;
		}
		if(action_code.equalsIgnoreCase("toCopyInHead"))
		{
			String id = context.getString("Id",null);
			InHead obj = InHead.copy(InHead.fetch(con,id));
			InHeadPageData data = (InHeadPageData)PageData.fromTable(obj,InHeadPageData.class);
			context.setValue("InHeadPageData",data);
			context.setNextUrl(path+"InHeadEdit.jsp");
			return;
		}
		if(action_code.equalsIgnoreCase("saveInHead"))
		{
			context.setErrorUrl(path+"InHeadEdit.jsp");
			saveInHead(con,context,loginContext);
			backInHead(con,context,path);
			return;
		}
		if(action_code.equalsIgnoreCase("saveAndNewInHead"))
		{
			context.setErrorUrl(path+"InHeadEdit.jsp");
			saveInHead(con,context,loginContext);
			InHead obj = InHead.fetch();
			InHeadPageData data = (InHeadPageData)PageData.fromTable(obj,InHeadPageData.class);
			context.setValue("InHeadPageData",data);
			context.setNextUrl(path+"InHeadEdit.jsp");			
			return;
		}
		if(action_code.equalsIgnoreCase("backListInHead"))
		{
			backInHead(con,context,path);
			return;
		}
		
		//add by Wing start
		if(action_code.equalsIgnoreCase("exportInHead"))
        {
			LoginContext loginInfo = LoginContext.get(context);
			User user=loginInfo.getUser();
			isTel=user.getTel().equals("1");
            exportInHead(con,context,path);
            return;
        }
		//add by Wing end

		Logger.throwException("InHeadSrv","unknown action_code="+action_code);
	}
}
